<template>
  <TresDirectionalLight :position="[-0.5, 5, 1.5]" :intensity="1" />
  <primitive v-if="scene" :object="scene" />
</template>

<script setup lang="ts">
import * as THREE from "three";
import { TextureLoader } from "three";
import { useGraph, useLoader } from "@tresjs/core";
import { useAnimations } from "@tresjs/cientos";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";

const emits = defineEmits(["animationEnd"]);
const { state: model } = await useLoader(GLTFLoader, "./model/t1-3.glb");
const { state: texture } = await useLoader(TextureLoader, "./ui/content3.png");
// 关键设置：优化清晰度
texture.value.anisotropy = 1;
texture.value.colorSpace = THREE.SRGBColorSpace;
texture.value.generateMipmaps = false; // 确保生成Mipmap（通常默认true）
texture.value.magFilter = THREE.NearestFilter; // 关键设置：放大时使用最近邻过滤，保持锐利
texture.value.minFilter = THREE.LinearFilter;

const graph = useGraph(model.value?.scene as any);
console.log("graph:", graph.value);
// 提取模型
const scene = graph.value?.nodes.Scene;
console.log("scene:", scene);

// 隐藏zhishe_mesh
if (graph.value?.nodes.zhihe_mesh) {
  graph.value.nodes.zhihe_mesh.visible = false;
}

// 设置材质
if (scene?.children[1]) {
  scene?.children[1].children.forEach((child: any) => {
    if (child.isMesh) {
      child.material = new THREE.MeshBasicMaterial({
        name: "02 - Default",
        color: new THREE.Color("#e7ba81"), // 光泽颜色
        map: texture.value,
        side: 2,
      });
    }
  });
}

// 设置位置和旋转
scene?.position.set(-0.5, 5, 1.5);
scene?.rotation.set(
  Math.PI * (-75 / 180),
  Math.PI * (-50 / 180),
  Math.PI * (-20 / 180)
);

// 播放动画
const { actions, mixer } = useAnimations(
  model.value.animations,
  graph.value?.nodes.Scene as any
);
// 监听动画结束事件
mixer.value.addEventListener("finished", (e) => {
  const name = e.action.getClip().name;
  if (name === "Root|Take 001|BaseLayer") {
    emits("animationEnd"); // 触发自定义事件
  }
});
Object.keys(actions).forEach((key) => {
  const animation = actions[key];
  animation?.setLoop(THREE.LoopOnce, 1); // 设置为仅播放一次
  animation?.play();
});
</script>
